package com.qing.demo.netty.client;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.socket.SocketChannel;


/**
 * @author caozhipeng
 * @date 2025/7/25
 */
public class MyClientHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        SocketChannel socketChannel=(SocketChannel)ctx.channel();
        System.out.println("客户端链接报告开始！");
        System.out.println("客户端链接报告信息：本客户端链接到服务器。ChannelID="+socketChannel.id());
        System.out.println("客户端链接报告结束！");
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("断开链接："+ctx.channel().localAddress().toString());

//        使用过程中断线重连；实际场景需要关闭线程池，并且通过ping的响应来判断是否断线
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    new NettyClient().connect("127.0.0.1",7379);
                    System.out.println("尝试重新连接");
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }).start();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
        cause.printStackTrace();
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("服务端回复信息："+ JSONUtil.toJsonStr(msg));
    }
}
